import Vue from 'vue'
import Router from 'vue-router'
import routerList from './router-list.js'
import routerStore from '@/router-store.js'
import Storage from './utils/storage.js'

Vue.use(Router)

function loadCompo (component) {
  return () => import(`@/${component}.vue`)
}
/**
 * 添加路由
 * @param {*} path 请求uri
 * @param {*} view 视图位置
 */

const addroute = (path, view,meta) => {
  return {
      name: view,
      path: path,
      meta: meta,
      component: loadCompo(view)
  }
}

let routes = [
  {path: '/', component: loadCompo('index')},
  {path: '/login', component: loadCompo('login')},
  {path: '/avatar', component: loadCompo('views/avatar-edit-compo')},
]

/**
* 重构路由
*/

let menus = {
  path: '/menus',
  component: loadCompo('menus'),
  children: [
    {
      path: '/',
      component: loadCompo('dashboard'),
    }
  ]
}

routerList.forEach(rt => {
  rt.features.forEach(feature => {
    const path = '/'+rt.hash + '/' + feature.hash;
    const view = 'views'+path;
    // console.log('注入path:',path,',compo:',view,'到路由');
    menus.children.push(addroute(path, view,feature))
  })
})
routes.push({path: '*', component: loadCompo('errors')})
routes.push(menus)

const router = new Router({
   // mode: 'history',
  scrollBehavior: () => ({ y: 0 }),
  routes
})

router.beforeEach((to, from, next) => {
  // console.log('router-from:',from);
  // console.log('router-to:',to);
  // console.log('router-next:',next);
  
  if (to.meta) {
    routerStore.set(to.meta)
  }
  if (to.matched.some(r => r.meta.requireAuth)) {  // 判断该路由是否需要登录权限
      const _curuser = Storage.curuser();
      if (!_curuser) {
          next({
              replace: true,
              path: '/login',
              query: { redirect: to.fullPath }
          })
      }
  }
  next();
})

router.afterEach(route => {
  document.body.scrollTop = 0
  document.documentElement.scrollTop = 0
  window.onscroll = null
  // console.log('测试路由之后')
})

export default router